package com.example.utils.image;

import com.example.utils.Config;
import com.example.utils.DateUtils;
import com.example.utils.FileUtils;
import com.example.utils.MathUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*;
import java.util.List;

public class ImageUtils {

    /**已经播放过的图片
     *
     */
    private  static Map<String,String> alreadyImages = new HashMap<String, String>();
    /**剩余图片组
     *
     */
    private static Map<String,String> nextImages = new HashMap<String, String>();
    /**当前下标
     *
     */
    private static int index = 0;


    /**
     * 图片钝化
     *
     * @param originalPic
     * @return
     */
    public static final BufferedImage getDlurPicture(BufferedImage originalPic) {
        int imageWidth = originalPic.getWidth();
        int imageHeight = originalPic.getHeight();

        BufferedImage newPic = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_3BYTE_BGR);

        float[] data = {0.0625f, 0.125f, 0.0625f, 0.125f, 0.125f, 0.125f,
                0.0625f, 0.125f, 0.0625f};

        Kernel kernel = new Kernel(3, 3, data);
        ConvolveOp co = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        co.filter(originalPic, newPic);
        return newPic;
    }

    public static final BufferedImage getSharperPicture(BufferedImage originalPic) {
        int imageWidth = originalPic.getWidth();
        int imageHeight = originalPic.getHeight();

        BufferedImage newPic = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_3BYTE_BGR);
        float[] data =
                {-1.0f, -1.0f, -1.0f, -1.0f, 10.0f, -1.0f, -1.0f, -1.0f, -1.0f};

        Kernel kernel = new Kernel(3, 3, data);
        ConvolveOp co = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        co.filter(originalPic, newPic);
        return newPic;
    }

    /**
     * 获取发言平常使用的图片
     *
     * @param url
     * @return
     */
    public static String handlerUsuallyImage(String url) {
        String fileName = DateUtils.getYYYYMMDDHHMMSS() + ".jpg.cqimg";
        String qqPath = "/usually/" + fileName;
        String filePath = Config.COOLQ_IMAGE_PATH+"/usually/" + fileName;
        File file = new File(Config.COOLQ_IMAGE_PATH+"/usually/", fileName);
        InputStream inputStream = HttpUtils.getInputStreamByGet(url);
        HttpUtils.saveData(inputStream, file);
        return qqPath;
    }

    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

    /**
     * 获取文件夹中文件的MD5值
     *
     * @param file
     * @param listChild ;true递归子目录中的文件
     * @return
     */
    public static Map<String, String> getDirMD5(File file, boolean listChild) {
        if (!file.isDirectory()) {
            return null;
        }
        //<filepath,md5>
        Map<String, String> map = new HashMap<String, String>();
        String md5;
        File files[] = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isDirectory() && listChild) {
                map.putAll(getDirMD5(f, listChild));
            } else {
                md5 = getFileMD5(f);
                if (md5 != null) {
                    map.put(f.getPath(), md5);
                }
            }
        }
        return map;
    }

    /**获取Round目录的下一张图片
     *
     * @return String[]  0 图片名称 1 已经播放的图片 2剩余播放的图片
     */
    public static String[] getNextRoundImage(){
        String fileName = null;

        // 初始化
        if(alreadyImages.size()<=0&&nextImages.size() <=0) {
            flushNextImages();
        // 如果播放完啦 那么从第一张继续开始
        }else if(alreadyImages.size()>0&&nextImages.size()==0){
            clearAlreadyImages();
            flushNextImages();
        }
        //获取未播放的图片
        Set<String> strings = nextImages.keySet();
        Iterator<String> iterator = strings.iterator();
        if(iterator.hasNext()){
            fileName = iterator.next();
            nextImages.remove(fileName);
            alreadyImages.put(fileName,DateUtils.getYYYYMMDDTime());
        }
        return new String[]{"/round/"+fileName,alreadyImages.size()+"",nextImages.size()+""};
    }

    public static void clearAlreadyImages(){
        alreadyImages.clear();
    }

    public static void flushNextImages(){
        // 获取所有图片
        List<String> fileNames = FileUtils.getFileNames(Config.ROUND_PATH);
        // 放到下一张图片组重
        for (String fileName : fileNames) {
            // 如果在next中不存在 并且没有播放过
            if(!nextImages.containsKey(fileName)&&!alreadyImages.containsKey(fileName)){
                nextImages.put(fileName,DateUtils.getYYYYMMDDTime());
            };
        }
    }

    /**获取立绘图片
     * @param id  装备ID
     * @return 图片
     */
    public static Image getAnimationPic(int id){
        String path = Config.ANIMATION_PATH;
        File file = new File(path+"\\"+id+".png");
        if(file.exists()){
            try {
                return ImageIO.read(file);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public static String getRoundImage(){
        List<String> fileNames = FileUtils.getFileNames(Config.ROUND_PATH);
        return "/round/"+fileNames.get(MathUtils.randInt(fileNames.size()-1,0));
    }

    public static String getDragonKingImage(String cardName){
        cardName = "> "+cardName+" <";
        List<String> fileNames = FileUtils.getFileNames(Config.Dragon_King_IMAGE_PATH);
        int i = MathUtils.randInt(fileNames.size()-1,0);
        System.out.println(i);
        String name = fileNames.get(i);
        String newName = DateUtils.getYYYYMMDDHHMMSS()+name;
        File img = new File(Config.Dragon_King_IMAGE_PATH+"\\"+name);
        File newImg = new File(Config.Dragon_King_IMAGE_PATH+"\\temp\\"+newName);
        if(img.exists()){
            try {
                Image image = ImageIO.read(img);
                int height = image.getHeight(null);
                int width = image.getWidth(null);
                BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
                Graphics2D graphics = bufferedImage.createGraphics();
                name = name.substring(0,name.indexOf('.'));
                String[] index = name.split("_");
                if(index.length >=2){
                   int left = Integer.parseInt(index[0]);
                   int top = Integer.parseInt(index[1]);
                   graphics.drawImage(image,0,0,null);
                   //消除文字锯齿
                   graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                   graphics.setColor(new Color(10, 6, 1));
                   graphics.setFont(new Font("微软雅黑",Font.BOLD,40));
                   left=left-(cardName.getBytes().length/2)*18;
                   graphics.drawString(cardName,left,top);
                   graphics.dispose();
                   ImageIO.write(bufferedImage,"png",newImg);
                   return "/dragonKing/temp/"+newName;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        /*File file1 = new File("F:\\workspace_acg\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\acgweb\\uploads\\task\\1495872495006.jpg");
        String s = file1.getPath();
        File file2 = new File("F:\\workspace_acg\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\acgweb\\uploads\\task\\1\\20170527\\1495872475363.jpg");
        System.out.println(getFileMD5(file1).equals(getFileMD5(file2)));
        System.out.println(s);*/
        String dragonKingImage = getDragonKingImage("> 陌殇 <");
        System.out.println(dragonKingImage);

    }
}
